<template>
  <div class="dept-distribution-container">
    <h2>部门资产分布</h2>
    
    <el-row :gutter="20">
      <el-col :span="24" :lg="10">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>部门资产数量分布</span>
              <el-select v-model="chartType" size="small" @change="changeChartType">
                <el-option label="柱状图" value="bar"></el-option>
                <el-option label="饼图" value="pie"></el-option>
                <el-option label="折线图" value="line"></el-option>
              </el-select>
            </div>
          </template>
          <div ref="chartContainer" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="24" :lg="14">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>部门资产详细数据</span>
              <el-select v-model="viewType" size="small">
                <el-option label="按数量" value="count"></el-option>
                <el-option label="按价值" value="value"></el-option>
              </el-select>
            </div>
          </template>
          <el-table :data="deptData" style="width: 100%">
            <el-table-column prop="deptName" label="部门名称"></el-table-column>
            <el-table-column prop="assetCount" label="资产数量" align="right">
              <template #header>
                <div class="header-with-percent">
                  <span>数量</span>
                  <span v-if="viewType === 'count'">(占比)</span>
                </div>
              </template>
              <template #default="scope">
                <div v-if="viewType === 'count'" class="value-with-percent">
                  <span>{{ scope.row.assetCount }}</span>
                  <span class="percent">{{ scope.row.countPercent }}</span>
                </div>
                <span v-else>{{ scope.row.assetCount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="assetValue" label="资产总值" align="right">
              <template #header>
                <div class="header-with-percent">
                  <span>价值(元)</span>
                  <span v-if="viewType === 'value'">(占比)</span>
                </div>
              </template>
              <template #default="scope">
                <div v-if="viewType === 'value'" class="value-with-percent">
                  <span>{{ formatCurrency(scope.row.assetValue) }}</span>
                  <span class="percent">{{ scope.row.valuePercent }}</span>
                </div>
                <span v-else>{{ formatCurrency(scope.row.assetValue) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, watch, nextTick } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  name: 'DeptDistribution',
  setup() {
    const chartContainer = ref(null)
    const chartInstance = ref(null)
    const chartType = ref('bar')
    const viewType = ref('count')
    const deptData = ref([])
    const totalCount = ref(0)
    const totalValue = ref(0)

    // 获取部门分布数据
    const getDeptDistribution = async () => {
      try {
        const response = await axios.get('/api/statistics/dept-distribution')
        
        if (response.code === 200 && response.data) {
          deptData.value = response.data
          calculateTotalsAndPercentages()
          initChart()
        } else {
          // 使用模拟数据
          setMockData()
        }
      } catch (error) {
        console.error('获取部门分布数据失败:', error)
        setMockData()
      }
    }

    // 设置模拟数据
    const setMockData = () => {
      deptData.value = [
        { deptName: '技术部', assetCount: 120, assetValue: 850000 },
        { deptName: '财务部', assetCount: 65, assetValue: 320000 },
        { deptName: '人力资源部', assetCount: 45, assetValue: 280000 },
        { deptName: '市场部', assetCount: 80, assetValue: 460000 },
        { deptName: '行政部', assetCount: 30, assetValue: 190000 }
      ]
      calculateTotalsAndPercentages()
      initChart()
    }

    // 计算总和和百分比
    const calculateTotalsAndPercentages = () => {
      totalCount.value = deptData.value.reduce((sum, item) => sum + item.assetCount, 0)
      totalValue.value = deptData.value.reduce((sum, item) => sum + item.assetValue, 0)
      
      deptData.value.forEach(item => {
        item.countPercent = ((item.assetCount / totalCount.value) * 100).toFixed(1) + '%'
        item.valuePercent = ((item.assetValue / totalValue.value) * 100).toFixed(1) + '%'
      })
    }

    // 初始化图表
    const initChart = () => {
      nextTick(() => {
        if (!chartContainer.value) return
        
        if (chartInstance.value) {
          chartInstance.value.dispose()
        }
        
        chartInstance.value = echarts.init(chartContainer.value)
        
        const option = generateChartOption()
        chartInstance.value.setOption(option)
        
        window.addEventListener('resize', handleResize)
      })
    }

    // 生成图表配置
    const generateChartOption = () => {
      const xAxisData = deptData.value.map(item => item.deptName)
      const seriesData = deptData.value.map(item => viewType.value === 'count' ? item.assetCount : item.assetValue)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const dataIndex = params[0].dataIndex
            const dept = deptData.value[dataIndex]
            return `
              <div>${dept.deptName}</div>
              <div>资产数量: ${dept.assetCount} (${dept.countPercent})</div>
              <div>资产总值: ${formatCurrency(dept.assetValue)} (${dept.valuePercent})</div>
            `
          }
        },
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
      }
      
      if (chartType.value === 'bar') {
        option.xAxis = {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            rotate: 45
          }
        }
        option.yAxis = {
          type: 'value'
        }
        option.series = [{
          data: seriesData,
          type: 'bar',
          barWidth: '60%',
          label: {
            show: true,
            position: 'top',
            formatter: (params) => {
              if (viewType.value === 'count') {
                return params.value
              } else {
                return formatCurrencyShort(params.value)
              }
            }
          }
        }]
      } else if (chartType.value === 'pie') {
        option.series = [{
          type: 'pie',
          radius: '60%',
          data: deptData.value.map(item => ({
            value: viewType.value === 'count' ? item.assetCount : item.assetValue,
            name: item.deptName
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {c}\n({d}%)'
          },
          labelLine: {
            show: true
          }
        }]
      } else if (chartType.value === 'line') {
        option.xAxis = {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            rotate: 45
          }
        }
        option.yAxis = {
          type: 'value'
        }
        option.series = [{
          data: seriesData,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3
          },
          areaStyle: {
            opacity: 0.3
          }
        }]
      }
      
      return option
    }

    // 切换图表类型
    const changeChartType = () => {
      if (chartInstance.value) {
        const option = generateChartOption()
        chartInstance.value.setOption(option)
      }
    }

    // 格式化货币
    const formatCurrency = (value) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(value)
    }

    // 短格式货币
    const formatCurrencyShort = (value) => {
      if (value >= 10000) {
        return (value / 10000).toFixed(1) + '万'
      }
      return value.toString()
    }

    // 处理窗口大小变化
    const handleResize = () => {
      if (chartInstance.value) {
        chartInstance.value.resize()
      }
    }

    // 监听视图类型变化
    watch(viewType, () => {
      changeChartType()
    })

    onMounted(() => {
      getDeptDistribution()
    })

    return {
      chartContainer,
      chartType,
      viewType,
      deptData,
      changeChartType,
      formatCurrency
    }
  }
}
</script>

<style scoped>
.dept-distribution-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.chart-card,
.data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.header-with-percent {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  font-size: 12px;
}

.value-with-percent {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.percent {
  font-size: 12px;
  color: #909399;
}
</style>